﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Text;

namespace Server.Common
{
    public static class FileUtil
    {
        public static bool WriteFile(string path, byte[] fileBytes)
        {
            try
            {
                Log4Util.LogInstance.Info(typeof(FileUtil), $"开始将文件【{path}】写入本地");
                string dirPath = Path.GetDirectoryName(path);

                if (!Directory.Exists(dirPath)) Directory.CreateDirectory(dirPath);

                path = FileUtil.GetFileName(path);

                using (FileStream st = new FileStream(path, FileMode.Create))
                {
                    Log4Util.LogInstance.Info(typeof(FileUtil), $"文件写入对象创建完成");
                    Log4Util.LogInstance.Info(typeof(FileUtil), $"写入文件大小：{fileBytes.Length}");
                    st.Write(fileBytes, 0, fileBytes.Length);
                    return true;
                };
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }


        public static byte[] StreamToBytes(Stream sr)
        {
            try
            {
                byte[] bytes = new byte[sr.Length];
                sr.Position = 0;
                sr.Read(bytes, 0, bytes.Length);
                // 设置当前流的位置为流的开始
                sr.Seek(0, SeekOrigin.Begin);
                return bytes;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }


        public static string GetFileName(string filePath)
        {
            return filePath;
            int i = 0;

            //获取文件目录
            string fileDirectory = Path.GetDirectoryName(filePath);
            //获取文件名称
            string fileName = Path.GetFileNameWithoutExtension(filePath);
            //获取文件后缀
            string fileExtension = Path.GetExtension(filePath);

            while (File.Exists(filePath))
            {
                i++;
                filePath = $"{fileDirectory}/{fileName}({i}){fileExtension}";
            }
            return filePath;
        }
    }
}
